package com.job.client.company.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.job.client.common.minio.BucketNameConstant;
import com.job.client.common.minio.MinIOUtils;
import com.job.client.common.result.AppHttpCode;
import com.job.client.common.result.ResponseResult;
import com.job.client.common.utils.JwtTokenUtils;
import com.job.client.company.mapper.CompanyMapper;
import com.job.client.company.service.AuthenticationService;
import com.job.client.company.service.CategoryService;
import com.job.client.company.service.CompanyService;
import com.job.client.model.auth.pojo.User;
import com.job.client.model.company.dto.CompanyAuth;
import com.job.client.model.company.pojo.Company;
import com.job.client.model.rabbitmq.AuditConstant;
import com.job.client.model.rabbitmq.MysqlToEsGDSNConstant;
import com.job.feign.client.posts.PostsFeign;
import com.mysql.cj.util.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 公司详情表 服务实现类
 * </p>
 *
 * @author fkl
 * @since 2023-12-07
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PostsFeign postsFeign;
    @Autowired
    private CategoryService categoryService;
    @Override
    public ResponseResult getCompanyById(String companyId) {
        Company company = companyMapper.selectById(companyId);
        if(company==null){
            return ResponseResult.ErrorResult(AppHttpCode.FAIL);
        }
        return ResponseResult.OkResult(company);
    }

    @Override
//    TODO
    public ResponseResult authUser(String authStr,HttpServletRequest request) {
        if(authStr.charAt(0) == '"'){
            authStr = authStr.substring(1,authStr.length()-1);
        }
        if(authStr==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        QueryWrapper<Company> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("ciphe_key",authStr);
        Company company = companyMapper.selectOne(queryWrapper);
        if(company==null){
            return ResponseResult.ErrorResult(AppHttpCode.AUTHENTICATION_NO_COMPANY);
        }
        ResponseResult responseResult = getUserInfo(request);
        if(responseResult.getCode()!=200){
            return responseResult;
        }
        User user = (User) responseResult.getData();
        System.out.println(user);
        authenticationService.saveUser(user.getUserId(), company.getCompanyId());
        return ResponseResult.OkResult();
    }

    @Override
    public ResponseResult companyAuth(CompanyAuth companyAuth,HttpServletRequest request) {
        ResponseResult responseResult = getUserInfo(request);
        if(responseResult.getCode()!=200){
            return responseResult;
        }
        if(companyAuth==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        User user = (User) responseResult.getData();
        companyAuth.setUserId(user.getUserId());
        String DataStr = JSON.toJSONString(companyAuth);
        rabbitTemplate.convertAndSend(AuditConstant.EXCHANGE_AUDIT,AuditConstant.ROUTINGKEY_COMPANY,DataStr);
        return ResponseResult.OkResult();
    }

    @Override
    public ResponseResult getCompanyInfoByList(List<String> companyIds) {
        if(companyIds == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        List<Company> companyList = new ArrayList<>();
        for (String companyId : companyIds) {
            ResponseResult result = getCompanyById(companyId);
            if(result.getCode() != 200){
                return result;
            }
            companyList.add(JSON.parseObject(JSON.toJSONString(result.getData()),Company.class));
        }
        return ResponseResult.OkResult(companyList);
    }

    @Override
    public ResponseResult uploadProfile(MultipartFile file, HttpServletRequest request) {
        if(file==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        String[] split = file.getOriginalFilename().split("\\.");
        String contentType = split[split.length-1];
        String uuid = String.valueOf(UUID.randomUUID());  //使用uuid获得文件的扩展名
        String fileName = uuid+"."+contentType;
        try {
            MinIOUtils.uploadFile(BucketNameConstant.CLIENT_COMPANY,file,fileName,contentType);  //反斜杠是一个转义字符，所以需要使用两个反斜杠来表示一个实际的点
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseResult.ErrorResult(AppHttpCode.MINIO_UPLOAD_FAIL);
        }
        String avatarURL = MinIOUtils.getBasisUrl(BucketNameConstant.CLIENT_COMPANY, fileName);
//        TODO:发送rabbitm到后台审核公司头像
        return ResponseResult.OkResult(avatarURL);
    }

    @Override
    public ResponseResult updateProfile(String companyId, String profilePicture) {
        if(companyId == null || profilePicture == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        UpdateWrapper<Company> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("company_profile_picture",profilePicture).eq("company_id",companyId);
        int i = companyMapper.update(updateWrapper);
        if(i != 1){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        return ResponseResult.OkResult();
    }

    @Override
    public ResponseResult updateCompany(Company company) {
        if(company == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        ResponseResult result = categoryService.getCategoryName(String.valueOf(company.getCategoryId()));
        if(result.getCode() != 200){
            return result;
        }
        String categoryName = (String) result.getData();
        company.setCategoryName(categoryName);
        int i = companyMapper.updateById(company);
        // 发送rabbitmq执行数据同步
        rabbitTemplate.convertAndSend(MysqlToEsGDSNConstant.EXCHANGE_GDSN,MysqlToEsGDSNConstant.ROUTINGKEY_COMPANY,JSON.toJSONString(company));
        if(i != 1){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        return ResponseResult.OkResult();
    }

    @Override
    public ResponseResult uploadCompanyImage(MultipartFile file, HttpServletRequest request) {
        if(file==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        String[] split = file.getOriginalFilename().split("\\.");
        String contentType = split[split.length-1];
        String uuid = String.valueOf(UUID.randomUUID());  //使用uuid获得文件的扩展名
        String fileName = uuid+"."+contentType;
        try {
            MinIOUtils.uploadFile(BucketNameConstant.CLIENT_COMPANY,file,fileName,contentType);  //反斜杠是一个转义字符，所以需要使用两个反斜杠来表示一个实际的点
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseResult.ErrorResult(AppHttpCode.MINIO_UPLOAD_FAIL);
        }
        String avatarURL = MinIOUtils.getBasisUrl(BucketNameConstant.CLIENT_COMPANY, fileName);
        return ResponseResult.OkResult(avatarURL);
    }

    @Override
    public ResponseResult getCountByCompanyId(String companyId) {
        if(companyId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        Long count_boss = authenticationService.getAuthCount(companyId);
        ResponseResult result = postsFeign.getCountByCompanyId(companyId);
        if(result.getCode() != 200){
            return result;
        }
        Long count_posts = JSON.parseObject(JSON.toJSONString(result.getData()), Long.class);
        Map<String,Long> data = new HashMap<>();
        data.put("bossCount",count_boss);
        data.put("postsCount",count_posts);
        return ResponseResult.OkResult(data);
    }

    // 根据token获得用户信息
    // TODO:可以分装为一个公共函数
    public ResponseResult getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        // token为”“或者null则未登录
        if(StringUtils.isNullOrEmpty(token)){
            return ResponseResult.ErrorResult(AppHttpCode.LOGIN_AUTH);
        }
        User user = JwtTokenUtils.checkToken(token);
        // 其中有数据缺失则表示token被修改
        if(user.getUserId()==null || (user.getUsername()==null && user.getPhone()==null)){
            return ResponseResult.ErrorResult(AppHttpCode.TOKEN_ERROR);
        }
        return ResponseResult.OkResult(user);
    }
}
